﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Configuration;

namespace System.Web.UI
{
	public static class ClientScriptManagerExtensions
	{
		/* 
		<script type="text/javascript">
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		</script>
		<script type="text/javascript">
		try {
		var pageTracker = _gat._getTracker("UA-9453848-4");
		pageTracker._trackPageview();
		} catch(err) {}</script>
		*/
		[Obsolete]
		private const string GoogleAnalyticsJavaScript = @"
        <script type=""text/javascript"">
        /* Google-Analytics-Code */
        var gaJsHost = ((""https:"" == document.location.protocol) ? ""https://ssl."" : ""http://www."");
        document.write(unescape(""%3Cscript src='"" + gaJsHost + ""google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E""));
        </script>
        <script type=""text/javascript"">
        var pageTracker = _gat._getTracker(""{0}"");
        pageTracker._initData();
        pageTracker._trackPageview();
        /* Google-Analytics-Code */
        </script>";


		[Obsolete]
		public static void RegisterGoogleAnalytics(this ClientScriptManager manager, Type type)
		{
			const string registeredKey = "Google-Analytics";
			string googleAnalyticsKey = WebConfigurationManager.AppSettings["GoogleAnalyticsKey"];

			if (string.IsNullOrEmpty(googleAnalyticsKey))
				throw new ConfigurationErrorsException("app configs error:GoogleAnalyticsKey has not found!");

			if (!manager.IsStartupScriptRegistered(type, registeredKey))
			{
				manager.RegisterStartupScript(
					type,
					registeredKey,
					string.Format(GoogleAnalyticsJavaScript, googleAnalyticsKey)
					);
			}

		}
	}
}
